package resources.bean;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpServletRequest;

import resources.dao.AccountDAO;
import resources.pojo.account;
import resources.util.Tool;

@ManagedBean(name="login")
@SessionScoped
public class Login {
	public static account user;
	private account account;
	
	public void checkBrowser(){
		try{
			String useragent = ((HttpServletRequest)FacesContext.getCurrentInstance().getExternalContext().getRequest()).getHeader("User-Agent");
			System.out.println("Browser : " + useragent);
		}catch (Exception e) {
			e.printStackTrace(System.out);
		}
	}
	
	public void onload(){
//		checkBrowser();
		if(!Tool.isPostBack()){
			account = (account) Tool.session().getAttribute("account");
			if(account==null){
				account = new account();
			}else{
				Tool.redirect("index.html");
			}
		}
	}	
	
	public void onloadTop(){
		account = (account) Tool.session().getAttribute("account");
		if(account==null){
			Tool.redirect(FacesContext.getCurrentInstance().getExternalContext().getRequestContextPath()+"/login.html");
		}
	}
	
	
	public void login(){
		if(AccountDAO.checkLogin(account)!=null){
			Tool.initLoad();
			user = account;
			Tool.session().setAttribute("account", account);
			Tool.redirect("index.html");
		}
	}
	
	public void logout(){
		Tool.session().removeAttribute("account");
		Tool.redirect(FacesContext.getCurrentInstance().getExternalContext().getRequestContextPath()+"/login.html");
	}
	
	public account getAccount() {
		return account;
	}

	public void setAccount(account account) {
		this.account = account;
	}
}
